import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

const api = {}
let ajaxUrl = 'http://vote.uue.cn/api'
if (process.env.NODE_ENV === 'development') {
  ajaxUrl = 'http://localhost:34568/api'
}
api.ajaxUrl = ajaxUrl
api.http = axios.create({
  timeout: 3000
})

// 添加请求拦截器
api.http.interceptors.request.use(
  function(config) {
    // config.headers['Accept'] = 'application/x.edu.v1+json';
    const token = sessionStorage.getItem('token')
    if (token) {
      // 不加入非默认的header，否则会触发OPTIONS请求，token通过追加token参数的方式解决
      // config.headers['X-Access-Token'] = token
    }
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      if (token) {
        config.data.token = token
      }
      config.data = qs.stringify(config.data)
    }
    if (config.method === 'get' || config.method === 'delete') {
      if (token) {
        if (config.url.indexOf('?') !== -1) {
          config.url = config.url + '&token=' + token
        } else {
          config.url = config.url + '?token=' + token
        }
      }
    }
    return config
  },
  function(error) {
    Message({
      message: '请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.http.interceptors.response.use(
  function(response) {
    if (response.status === 200) {
      console.log(response.data)
      return response.data
    }
    return response
  },
  function(error) {
    const act = error.request.responseURL.split('/').pop()
    if ((error.response.data.code === 401 || error.response.data.code === 405) && act !== 'login') {
      Message({
        message: '您的会话已过期，请重新登陆',
        type: 'error'
      })
    } else {
      let desc = ''
      if (error.response.data.errors && error.response.data.errors.json) {
        desc = ' => ' + error.response.data.errors.json.message
      }
      Message({
        message: error.response.data.msg + desc,
        type: 'error'
      })
    }
    return Promise.reject(error.response)
  }
)
// 主要针对router的名字和输入的controller不一致的情况
api.getRouterName = function(controller) {
  const routers = {
    company: 'companies'// company的复数（router的名字）要变形
  }
  if (routers[controller]) {
    return routers[controller]
  } else {
    return controller + 's'
  }
}
api.service = {
  // 登录
  login: function(params) {
    return api.http.post(ajaxUrl + '/users/login', params)
  },
  list: function(controller, params) {
    return api.http.get(ajaxUrl + '/' + api.getRouterName(controller) + '/?' + qs.stringify(params))
  },
  menus: function(controller, params) {
    return api.http.get(ajaxUrl + '/' + api.getRouterName(controller) + '/menus?' + qs.stringify(params))
  },
  view: function(controller, params) {
    return api.http.get(ajaxUrl + '/' + api.getRouterName(controller) + '/' + params[controller + 'Id'])
  },
  edit: function(controller, params) {
    return api.http.put(ajaxUrl + '/' + api.getRouterName(controller) + '/' + params[controller + 'Id'], params)
  },
  add: function(controller, params) {
    return api.http.post(ajaxUrl + '/' + api.getRouterName(controller) + '', params)
  },
  remove: function(controller, params) {
    return api.http.delete(ajaxUrl + '/' + api.getRouterName(controller) + '/' + params.id)
  },
  batchRemove: function(controller, params) {
    return api.http.delete(ajaxUrl + '/' + api.getRouterName(controller) + '/' + params.ids)
  }
}
api.ajaxUrl = ajaxUrl
export default api
